"""
验证码数据库操作
"""
import random
from datetime import datetime, timedelta
from sqlalchemy.orm import Session
from sqlalchemy import and_, or_
from backend.app.models.verification import VerificationCode
from backend.app.utils.logger import logger


def generate_verification_code() -> str:
    """生成6位数字验证码"""
    return ''.join(random.choices('0123456789', k=6))


def create_verification_code(db: Session, email: str) -> VerificationCode:
    """创建新的验证码记录"""
    try:
        # 删除该邮箱的旧验证码
        old_codes = db.query(VerificationCode).filter(
            VerificationCode.email == email
        ).all()

        if old_codes:
            logger.info(f"删除旧验证码: email={email}, count={len(old_codes)}")
            for code in old_codes:
                db.delete(code)

        # 创建新验证码
        code = generate_verification_code()
        verification = VerificationCode(
            email=email,
            code=code,
            expires_at=datetime.utcnow() + timedelta(minutes=5)  # 延长到5分钟
        )
        db.add(verification)
        db.commit()
        db.refresh(verification)

        logger.info(f"创建新验证码: email={email}, code={code}")
        return verification

    except Exception as e:
        logger.error(f"创建验证码失败: {str(e)}", exc_info=True)
        db.rollback()
        raise


def verify_code(db: Session, email: str, code: str) -> bool:
    """验证验证码"""
    try:
        # 使用模型类方法验证
        return VerificationCode.verify_code(db, email, code)
    except Exception as e:
        logger.error(f"验证码验证过程发生错误: {str(e)}", exc_info=True)
        return False


def cleanup_expired_codes(db: Session):
    """清理过期的验证码"""
    try:
        expired_codes = db.query(VerificationCode).filter(
            or_(
                VerificationCode.expires_at < datetime.utcnow(),
                VerificationCode.is_used == True
            )
        ).all()

        if expired_codes:
            logger.info(f"清理过期验证码: count={len(expired_codes)}")
            for code in expired_codes:
                db.delete(code)
            db.commit()

    except Exception as e:
        logger.error(f"清理过期验证码失败: {str(e)}", exc_info=True)
        db.rollback()
